package com.cd.form.controller;

import com.cd.common.annotation.Log;
import com.cd.common.config.ProjectConfig;
import com.cd.common.constant.Constants;
import com.cd.common.controller.BaseController;
import com.cd.common.domain.AjaxResult;
import com.cd.common.domain.LoginUser;
import com.cd.common.enums.BusinessType;
import com.cd.common.util.StringUtils;
import com.cd.common.util.file.FileUploadUtils;
import com.cd.common.util.file.MimeTypeUtils;
import com.cd.form.api.FormService;
import com.cd.form.dto.ResultDataDto;
import com.cd.form.jpa.domian.FormComponent;
import com.cd.form.jpa.domian.FormInstance;
import com.cd.form.jpa.domian.FormResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/form")
public class FormController extends BaseController {

    @Autowired
    private FormService formService;

    /**
     * @Description 表单实例相关
     * @Author lqq
     * @Date
     **/

    //表单实例获取
    @GetMapping("/getFormInstance")
    public AjaxResult getFormInstance(@RequestParam(value = "formId",required = false) Long formId,
                                      @RequestParam(value = "name", required = false) String name) {
        //如果formId name 均为null 则为按照权限全局搜索
        //如果name不为空 则为按名称搜索
        List<FormInstance> result = formService.getFormInstance(formId, name);
        return success(result);
    }

    //按照id获取当前表单信息
    @GetMapping("/getFormInfo/{formId}")
    public AjaxResult getFormInfo(@PathVariable(value = "formId") Long formId) {
        FormInstance result = formService.getFormInfo(formId);
        return success(result);
    }

    //表单实例创建
    @PostMapping("/createFormInstance")
    @Log(title = "表单创建", businessType = BusinessType.INSERT)
    public AjaxResult createFormInstance(@RequestBody FormInstance formInstance) {
        formService.createFormInstance(formInstance);
        return success("保存成功");
    }

    //表单实例修改
    @PostMapping("/updateFormInstance")
    @Log(title = "表单修改", businessType = BusinessType.UPDATE)
    public AjaxResult updateFormInstance(@RequestBody FormInstance formInstance) {
        formService.updateFormInstance(formInstance);
        return success("保存成功");
    }

    //表单实例废弃 仅管理员可使用 还是修改截止日期 没想到 待定

    /**
     * @Description 表单组件相关
     * @Author lqq
     * @Date
     **/

    //获取当前表单的组件
    @GetMapping("/getFormComponent/{formId}")
    public AjaxResult getFormComponentByFormId(@PathVariable(value = "formId") Long formId) {
        List<FormComponent> result = formService.getFormComponentByFormId(formId);
        return success(result);
    }

    //表单组件新增
    @PostMapping("/createFormComponent")
    @Log(title = "表单组件新增", businessType = BusinessType.INSERT)
    public AjaxResult createFormComponent(@RequestBody FormComponent formComponent) {
        formService.createFormComponent(formComponent);
        return success(formComponent);
    }

    //表单组件修改
    @PostMapping("/updateFormComponent")
    @Log(title = "表单组件修改", businessType = BusinessType.UPDATE)
    public AjaxResult updateFormComponent(@RequestBody FormComponent formComponent) {
        formService.updateFormComponent(formComponent);
        return success(formComponent);
    }

    //表单移除 按照id
    @PostMapping("/removeFormComponent")
    @Log(title = "表单组件移除", businessType = BusinessType.DELETE)
    public AjaxResult removeFormComponent(@RequestParam Long formComponentId) {
        formService.removeFormComponent(formComponentId);
        return success("删除成功");
    }

    //表单组件批量修改 不分新增修改
    @PostMapping("/updateFormComponentBatch")
    @Log(title = "表单批量修改", businessType = BusinessType.UPDATE)
    public AjaxResult updateFormComponentBatch(@RequestBody List<FormComponent> formComponents) {
        formService.updateFormComponentBatch(formComponents);
        return success("保存成功");
    }

    //复制已有的表单 按照form_id
    @PostMapping("/copyFormComponent")
    @Log(title = "表单复制", businessType = BusinessType.INSERT)
    public AjaxResult copyFormComponent(@RequestParam Long fromFormId,
                                        @RequestParam Long currentFormId) {
        formService.copyFormComponent(fromFormId, currentFormId);
        return success("保存成功");
    }

    //表单提交
    @PostMapping("/submitForm")
    @Log(title = "表单提交", businessType = BusinessType.OTHER)
    public AjaxResult submitForm(@RequestBody FormResult formResult) {
        formService.submitForm(formResult);
        return success("保存成功");
    }

    //按照formId获取所有表单提交
    @GetMapping("/getFormResult/{formId}")
    @Log(title = "表单结果查看", businessType = BusinessType.OTHER)
    //修改
    public AjaxResult getFormResult(@PathVariable(value = "formId") Long formId,
                                    @RequestParam(value = "status", required = false) Integer status) {

        List<FormResult> result = null;
        if (status == null) {
            //无条件查询 用于首页查看所有提交
            result = formService.getFormResult(formId);
        } else {
            //条件查询 用于过滤或者审批页面
            result = formService.getFormResultWithStatus(formId, status);
        }

        return success(result);
    }

    //修改状态 updateStatus
    @PostMapping("/updateStatus")
    @Log(title = "表单状态修改", businessType = BusinessType.UPDATE)
    public AjaxResult updateStatus(@RequestBody FormResult formResult) {
        formService.updateStatus(formResult);
        return success(formResult);
    }

    //图片上传
    @PostMapping("/upload/file")
    public AjaxResult uploadFile(@RequestParam("fileName") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            //LoginUser loginUser = getLoginUser();
            String filePath = FileUploadUtils.upload(ProjectConfig.getFilePath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", filePath);
            return ajax;
        }
        return error("上传图片异常，请联系管理员");
    }

    //获取图片地址
    @GetMapping("/getUrl")
    public AjaxResult getUrl(@RequestParam String filePath) {
        try {
            // 1. 安全校验
            if (filePath.contains("..")) {
                return error("非法路径");
            }

            // 2. 检查文件扩展名
//            if (!isAllowedExtension(filePath)) {
//                return ResponseEntity.badRequest().body("不支持的文件类型");
//            }

            // 3. 构建完整路径
            //Path fullPath = Paths.get(baseDir).resolve(filePath).normalize();
            String localPath = ProjectConfig.getProfile();
            String downloadPath = localPath + StringUtils.substringAfter(filePath, Constants.RESOURCE_PREFIX);
            Path fullPath = Paths.get(downloadPath).normalize();
            // 4. 验证文件存在且可读
            if (!Files.exists(fullPath) || !Files.isReadable(fullPath)) {
                return error("文件不存在");
            }

            // 5. 返回文件信息
            Map<String, Object> response = new HashMap<>();
            response.put("url", filePath); // 相对路径
            response.put("size", Files.size(fullPath));
            response.put("mimeType", Files.probeContentType(fullPath));
            response.put("lastModified", Files.getLastModifiedTime(fullPath).toMillis());

            return success(response);

        } catch (Exception e) {
            return error("文件服务异常: " + e.getMessage());
        }
    }

    //表单数据excel导出
    @GetMapping("/export/{formId}")
    public void export(@PathVariable(value = "formId") Long formId, HttpServletResponse response) {
        formService.excelImport(formId,response);
    }

}
